// src/stores/login.ts
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { loginStore, confirmBrand, GetBrandByUserId, getBrandById } from '@/common/net/api'
import type {
  LoginRequest,
  LoginResponse,
  User, Brand
} from "@/common/types/userType";
import router from "@/router";
export const useLoginStore = defineStore('login', () => {
  const user = ref<User | null>(null);
  const brands = ref<Brand[]>([]);
  const brand = ref<Brand>({
    brandId: -1, brandLogoUrl: "", brandName: "",
  });
  const isAdmin = ref<boolean>(false);
  const selectedBrandId = ref<string | null>(null);
  const token = ref<string | null>(localStorage.getItem("token") || null);
  async function handleLogin(data: LoginRequest): Promise<LoginResponse | null> {
    try {
      const response = await loginStore(data);
      if (response.state) {
        user.value = response.data.user;
        brands.value = response.data.brands;
        return response;
      } else {
        alert(response.msg);
        return null;
      }
    } catch (error) {
      console.error('Login error:', error);
      alert('登录失败，请检查网络或联系管理员');
      return null;
    }
  }
  // @ts-ignore
  async function handleConfirmBrand(brandId: string): boolean {
      const userId = user.value?.userId;
      if (!userId) {
        throw new Error('User ID is not available');
      }
      await confirmBrand( userId, brandId ).then(res=> {
        selectedBrandId.value =brandId;
        if (res.state) {
          // 登录成功，保存 token
          // @ts-ignore
          localStorage.setItem("token", res.data as string);
          localStorage.setItem("brandId", brandId);
          // 获取信息
          getBrandById().then((brandValue)=>{
            console.log(brandValue);
             brand.value=brandValue.data as Brand;
          })
          // 查询店铺信息
          isAdmin.value = brandId === "0";
          router.push("/")
          return true;
        } else {
          return false;
        }
      })
  }
  function getBrand(){
    getBrandById().then((brandValue)=>{
      brand.value=brandValue.data.data as Brand;
    })
    return brand.value.brandId;
  }
  function logout() {
    // 清除用户信息
    user.value = null;
    brands.value = [];
    brand.value = { brandId: -1, brandLogoUrl: "", brandName: "" };
    selectedBrandId.value = null;
    token.value = null;
    isAdmin.value = false;
    localStorage.removeItem("token");
    router.push('/login');
  }

  return { user, brands,brand, selectedBrandId, handleLogin, handleConfirmBrand,isAdmin,logout,getBrand };
});
